package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.service.goods.SkuSearchService;
import com.qingcheng.util.WebUtil;
import net.sf.json.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * @author 岳剑飞
 * @Company http://www.ithiema.com
 */
@Controller
public class SearchController {
    @Reference
    private SkuSearchService skuSearchService;

    @GetMapping("/search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) throws Exception {
        //字符集处理
        searchMap = WebUtil.convertCharsetToUTF8(searchMap);

        //"spec.版本" -> "8GB 128GB" --> "8GB+128GB"
        //因为前台传入的数据  +  号会丢失, 再次进行替换处理
        for (String key : searchMap.keySet()) {
            if ("spec.版本".equals(key)) {
                String value = searchMap.get(key);
                value = value.replace(" ", "+");
                searchMap.put(key, value);
            }
        }

        //排序参数容错处理
        if (searchMap.get("sort") == null) {
            searchMap.put("sort", "");
        }
        if (searchMap.get("sortOrder") == null) {
            searchMap.put("sortOrder", "DESC");
        }

        //接受页码处理,如果不传递页码默认为第1页
        if (searchMap.get("pageNo") == null) {
            searchMap.put("pageNo", "1");
        }
        //封装返回当前页数
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo", pageNo);


        //url处理，获取到前台传入的url 地址
        StringBuffer url = new StringBuffer("/search.do?");
        for (String key : searchMap.keySet()) {
            url.append("&" + key + "=" + searchMap.get(key));
        }
        model.addAttribute("url", url);


        //远程调用接口，查询商品列表
        Map result = skuSearchService.searchMap(searchMap);

        //对分页进行处理
        Long totalPages = (Long) result.get("totalPages"); // 得到总页数
        int startPage = 1; //开始页码
        int endPage = totalPages.intValue(); // 截止页码
        if (totalPages > 5) {
            startPage = pageNo - 2;
            endPage = pageNo + 2;

            if (startPage < 1) {
                startPage = 1;
                endPage = 5;
            }
            if (endPage > totalPages) {
                endPage = totalPages.intValue();
                startPage = endPage - 4;
            }
        }
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage", endPage);


        model.addAttribute("result", result);
        //取消分类过滤，将查询条件回调回前台
        model.addAttribute("searchMap", searchMap);
        return "search";
    }

}
